<template>
  <div class="player-container">
    <h2>正在播放: {{ info?.title }}</h2>
    <HlsPlayer :masterUrl="url" @videoEnded="videoEnded" />
    <div class="parts">
      <template v-for="item in urlArr" :key="item.id">
        <el-button
          size="large"
          :type="item.url === url ? 'primary' : 'default'"
          @click="url = item.url"
          >第{{ item.sort }}集</el-button
        >
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import HlsPlayer from '@/components/HlsPlayer.vue'
import { getVideoParts, getVideoInfo } from '@/api/video/manage'

const info = ref<Videos>()

const url = ref('')

interface IPart extends VideoPart {
  url: string
}

const urlArr = ref<IPart[]>()

function videoEnded() {
  const index = urlArr.value!.findIndex((item) => item.url === url.value)
  // 最后一个
  if (index === urlArr.value!.length - 1) {
    url.value = urlArr.value![0].url
  } else {
    url.value = urlArr.value![index + 1].url
  }
}

const videoId = ref(0)
const route = useRoute()
onMounted(() => {
  videoId.value = Number(route.query.videoId ?? '')
  getVideoInfo(videoId.value).then((res) => {
    if (res.code === 200) {
      info.value = res.data
    }
  })
  getVideoParts(videoId.value).then((res) => {
    if (res) {
      if (res.code === 200) {
        urlArr.value = res.data?.map((item) => {
          return {
            ...item,
            url: `${import.meta.env.VITE_API_BASE_URL}/player/hls/${item.id}/master.m3u8`
          }
        })
        url.value = urlArr.value![0].url
      }
    }
  })
})
</script>

<style lang="scss" scoped>
.player-container {
  padding: 0 10%;
  width: 80%;
  display: flex;
  flex-direction: column;
  .parts {
    margin-top: 12px;
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 8px;
    .el-button {
      margin: 0;
    }
  }
}
</style>
